<template>
	
	<view class="notice">
		<uni-breadcrumb separator="/">
			<uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">
				{{route.name}}
			</uni-breadcrumb-item>
		</uni-breadcrumb>
		<loading v-if="loading"></loading>
		<uni-forms 
			v-show="!loading" ref="form" :model="formData" 
			validateTrigger="bind" label-width="300"
		>
			<uni-forms-item name="title" style="font-weight: bold;font-size:25px;">
				<view style=" width: 50%; margin:10px auto 0 auto; ">
					<uni-easyinput v-model="formData.title" style="font-size: 25px;text-align: center;" placeholder="输入标题" ></uni-easyinput>
				</view>
			</uni-forms-item>
			
			
			<uni-forms-item name="content" label="">
				<view class="editor" >
					 <webEdit v-model="formData.content" @blurEdit="onBlurEdit" ids="content"  style="width:100%;"></webEdit>
				</view>
			</uni-forms-item>
			<uni-forms-item name="abstract" label="公告摘要">
				<uni-easyinput type="textarea" v-model="formData.abstract"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="images" label="公告主图">
				<uni-file-picker v-model="formData.images" limit="3" title=" " :image-styles="imagestyle"></uni-file-picker>
			</uni-forms-item>
			<view >
				<uni-forms-item class="platform_type" name="type" label="公告类型:">
					<radio-group @change="radioChange" class="pagetitle" style="border:none;">
						<label class="pagetitle" v-for="(item, index) in items" :key="item.value">
							<view>
								<radio :value="item.value" :checked="index+1 === formData.type.value" />
							</view>
							<view>{{item.name}}</view>
						</label>
					</radio-group>
				</uni-forms-item>
			</view>
			<uni-forms-item class="platform_type" name="type" label="筛选分发:">
				<view class="target">
					<view class="item"
						v-for="(item,index) in target" :key="index" 
						@click="onTarget(index)"
						:class="index === targetIndex ? 'itemTow':'' "
					>
						{{item}}
					</view>
				</view>
				
				<swiper class="swiper"  :class="targetIndex===0?'swiperTow':targetIndex===2?'swiperThree':''" :current="targetIndex"  disable-touch >
						<swiper-item item-id="1">
							<view class="swiper-item one">
								<label style="display: flex; align-items: center;"  >
									<view>
										<radio  :checked="true" />
									</view>
									<view>全部可见</view>
								</label>
							</view>
						</swiper-item>
						<swiper-item item-id="3" class="swiper-item " >
							<view class="search">
								<uni-easyinput errorMessage v-model="searchVal"  placeholder="搜索内容(可搜:昵称，手机号码,id)" ></uni-easyinput>
								<button size="mini" @click="eventSearch" >
									搜索
								</button>
							</view>
							<scroll-view :scroll-top="scrollTop" @scrolltolower="scrollBottom" scroll-y="true" class="scroll-y" >
								<view  class=" " >
									<checkbox-group  @change="onMultipleData" class="scroll-H">
										<label
											v-for="(item,index) in aloneData" class="item" :key="index"
										>
											<checkbox :value="item"	  :checked="onDefault(item._id._value)" />
											<view>
												<image v-if="item.avatar" :src="item.avatar+'?x-oss-process=image/resize,m_fixed,h_100,w_100'" mode="widthFix" style="width:70rpx;" ></image>
											</view>
											<view>
												<view class="_content">
													{{item.nickname}}
												</view>
												<view class="labelApp">
													{{item.mobile?item.mobile:item._id.users_address.length!=0?item._id.users_address[0].phone:'暂无手机号'}}
												</view>
											</view>
										</label>
										<label
											v-for="(item,index) in personData" :key="index" 
											v-show="!hidenData(item._id._value)"
										>
											<view class="item"   v-if="!hidenData(item._id._value)" >
												<checkbox :value="item"	  :checked="onDefault(item._id._value)" />
												<view>
													<image v-if="item.avatar" :src="item.avatar+'?x-oss-process=image/resize,m_fixed,h_100,w_100'" mode="widthFix" style="width:70rpx;" ></image>
												</view>
												<view>
													<view class="_content">
														{{item.nickname}}
													</view>
													<view class="labelApp">
														{{item.mobile?item.mobile:item._id.users_address.length!=0?item._id.users_address[0].phone:'暂无手机号'}}
													</view>
												</view>
											</view>
										</label>
									</checkbox-group>
								</view>
								<view style="padding:70px 0 ;text-align: center;">
									<text v-if="personData.length === 0" >
										暂无数据
									</text>
								</view>
							</scroll-view>	
						</swiper-item>
				</swiper>
			</uni-forms-item>
			
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {validator,
		onPersonUid,
		onDefault,
	} from '@/js_sdk/validator/notice.js';
	import {publicData ,publicFun } from "./user.js"
	import Util from '@/js_sdk/validator/util.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'notice';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}
	export default {
		data() {
			let formData = {
				"title": "",
				"images": null,
				"abstract": "",
				"content": "",
				"platform_type": '__UNI__8A62930',
				"is_forced_reading": false,
				"type": {
					value: 1,
					name: '平台公告'
				},
				"targetSend": {
					"platform": "全部发送",
					"label_arr": [],
					"screens_uid": []
				}
			}
			return {
				routes: [
					{to: "/pages/index/index",name: "首页",},
					{to: "",name: "通知管理" },
					{to: "./list",name: "用户通知" },
					{to: "",name: "修改通知" }
				],
				formData,
				multipleData:[],
				skip:0,
				targetIndex:0,
				personData:[],
				selectTimeVal:0,
				where:{},
				label_arr:[],
				formOptions: {},
				aloneData:[],
				rules: {
					...validator
				},
				...publicData
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}

		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			
			this.getPersonData()
		},
		methods: {
			...publicFun,
			hidenData(id){
				return this.label_arr.screens_uid.some(function (element) {
					return id == element
				});
			},
			editData(){
				const dbCmd = db.command
				const _this = this
				let usersField =  "avatar,nickname,register_env,mobile,status,_id"
				let addressField = "_id,user_id,title,phone"
				let usersData = db.collection("uni-id-users").field(usersField).getTemp({getOne:false})
				let usersAddress = db.collection("users_address").field(addressField).getTemp({getOne:true})
				db.collection(usersData,usersAddress).where({
					"_id._value":dbCmd.in(this.label_arr.screens_uid)
				}).get({getOne:false}).then( res => {
					let data = res.result.data
					this.aloneData = data
					this.formData.targetSend.platform = '单独发送'
					this.formData.targetSend.label_arr = this.aloneData
					// console.log(this.formData)
				})
				
			},
			// 返回默认值
			onDefault(item){
				return onDefault(item,this.label_arr)
			},
			/**
			 * 验证表单并提交
			 */
			async submit() {
				let multipleData = this.formData.targetSend.label_arr
				if (this.targetIndex === 1) {
					let tampdata =  await onPersonUid(multipleData,'__UNI__8A62930')
					this.formData.targetSend.screens_uid = tampdata.result
					delete this.formData.targetSend.label_arr
				}else {
					this.formData.targetSend.screens_uid = []
				}
				this.formData.create_date = Date.now()
				// console.log(this.formData)
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					delete this.formData._id
					return this.submitForm(this.formData)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"title,abstract,content,images,targetSend,type,shop_id,is_forced_reading,platform_type,create_date" ).get({customUI: true}).then( res => {
					const data = res.result.data[0]
					// console.log(data)
					this.targetIndex = this.target.indexOf(data.targetSend.platform)
					this.label_arr = Util.deepCopy(data.targetSend)
					this.loading = false
					if(this.targetIndex===1) {
						this.editData()
					}
					if (data) {
						this.formData = data
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
<style scoped lang="scss">
	@import '@/pages/notice/user/user.css' ;
	.notice{
		padding:50rpx;
	}
</style>